import MD5 from 'crypto-js/md5';
/**
 * 签名工具类（对应Java的ApiSignUtils）
 */
class ApiSignUtils {

    /**
     * 生成32位随机英文数字小写字符串
     */
    static generate32BitString() {
        const charSet = 'abcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < 32; i++) {
            const randomIndex = Math.floor(Math.random() * charSet.length);
            result += charSet.charAt(randomIndex);
        }
        return result;
    }

    /**
     * MD5加密方法
     */
    static md5(input) {
        return MD5(input).toString();
    }

    /**
     * 生成完整的签名信息（对应Java的generateSignature方法）
     */
    static generateSignature() {
        // 1. 生成三个32位随机字符串
        const str1 = this.generate32BitString();
        const str2 = this.generate32BitString();
        const str3 = this.generate32BitString();

        // 2. 获取当前毫秒时间戳
        const timestamp = Date.now();
        const tmp = timestamp.toString();

        // 3. 截取时间戳后三位，不足三位前面补0
        const lastThree = tmp.substring(Math.max(0, tmp.length - 3)).padStart(3, '0');

        // 解析个位、十位、百位数值
        const units = parseInt(lastThree.charAt(2)) || 1;
        const tens = parseInt(lastThree.charAt(1)) || 1;
        const hundreds = parseInt(lastThree.charAt(0)) || 1;

        // 4. 截取字符串尾部
        const slice1 = str1.substring(Math.max(0, str1.length - units));
        const slice2 = str2.substring(Math.max(0, str2.length - tens));
        const slice3 = str3.substring(Math.max(0, str3.length - hundreds));

        // 5. 拼接字符串并MD5加密
        const combined = slice1 + slice2 + slice3 + tmp;
        const sign = this.md5(combined);

        return {
            str1,
            str2,
            str3,
            sign,
            tmp
        };
    }
}

export default ApiSignUtils;